import Vue from "vue";
import VueRouter from "vue-router";
import LAYOUT from "../views/layout/index.vue";
import Login from "@/views/login/index.vue";
import { asyncRouter } from "./asyncRouter";
import Table from "@/views/table/index.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "layout",
    component: LAYOUT,
  },
  {
    path: "/login",
    name: "login",
    component: Login,
  },
  ...asyncRouter,
];

const router = new VueRouter({
  mode: "hash",
  routes,
});

router.beforeEach((to, from, next) => {
  console.log(router);
  next();
});

// 重写了 push、replace 方法：
//   如果用户传入了回调，则保留原行为；
//   如果没传回调，则默认传入空函数 () => {} 避免报错。
// Vue Router 3.x 或以上版本（如 vue-router@3.6+），这个问题已经被官方修复了
let originPush = VueRouter.prototype.push;
let originReplace = Vue.prototype.originReplace;

VueRouter.prototype.push = function (location, res, rej) {
  if (res && rej) {
    originPush.call(this, location, res, rej);
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

VueRouter.prototype.replace = function (location, res, rej) {
  if (res && rej) {
    originReplace.call(this, location, res, rej);
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

export default router;
